package com.cn.kehong.service;

import com.cn.kehong.api.IPlanYearDetailService;
import com.cn.kehong.api.IPlanYearService;
import com.cn.kehong.dao.PlanYearMapper;
import com.cn.kehong.domain.PlanYear;
import com.cn.kehong.domain.PlanYearDetail;
import com.cn.kehong.domain.PlanYearExample;
import com.cn.kehong.utils.CollectionsUtil;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.QueryForm;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Service
public class PlanYearServiceImpl implements IPlanYearService {

    @Autowired
    private PlanYearMapper planYearMapper;

    @Autowired
    private IPlanYearDetailService planYearDetailService;

    @Override
    public List<PlanYear> getPlanYearList(QueryForm queryForm) throws Exception {
        int count = planYearMapper.selectPlanYearListCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<PlanYear> planYears = planYearMapper.selectPlanYearList(queryForm);
        planYears.get(0).setCount(count);
        return planYears;
    }

    @Override
    public PlanYear getYearPlanByYear(String year) throws Exception {
        List<PlanYear> planYears = planYearMapper.selectYearPlanByYear(year);
        if(CollectionUtils.isEmpty(planYears)){
            return new PlanYear();
        }
        if(planYears.size() > 1){
            throw new Exception("年度计划异常，存在多个年度计划");
        }
        return planYears.get(0);
    }

    @Override
    public List<String> getSelectPlanYears() throws Exception {
        List<String> years = planYearMapper.selectPlanYears();
        if(CollectionUtils.isEmpty(years)){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
            String currentYear = simpleDateFormat.format(new Date());
            years.add(currentYear);
        }
        return years;
    }

    @Override
    public String addPlanYear(PlanYear planYear) throws Exception {
        String id = CommonUtil.generateRandomNum("planYear-");
        String year = planYear.getPlanYear();
        if(StringUtils.isEmpty(year)){
            return "年份不能为空！";
        }
        planYear.setId(id);
        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andPlanYearEqualTo(year).andStatusEqualTo(Constants.NORMAL_STATUS);
        int existCount = planYearMapper.countByExample(example);
        if(existCount > 0){
            return "年度报告已经存在，无法新增，只能修订！";
        }
        List<PlanYearDetail> planYearDetails = planYear.getPlanYearDetails();
        if(CollectionUtils.isEmpty(planYearDetails)){
            return "数据异常！";
        }
        for(PlanYearDetail detail:planYearDetails){
            detail.setPlanYearId(id);
        }
        int count = planYearMapper.insertSelective(planYear);
        if(count < 1){
            return "插入年度表异常！";
        }
        String resp = planYearDetailService.addPlanYearDetail(planYearDetails);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updatePlanYearVersion(PlanYear planYear) throws Exception {
        String id = planYear.getId();
        if(StringUtils.isEmpty(id)){
            return "主键为空！";
        }
        PlanYear exist = planYearMapper.selectPlanYearById(id);
        if(null == exist){
            return "未查询到年度计划！";
        }
        String planStatus = exist.getPlanStatus();
        if(StringUtils.equals(planStatus,"0")||StringUtils.equals(planStatus,"5")){
            return "年度计划在待执行状态,无需变更";
        }

        List<PlanYearDetail> planYearDetails = planYear.getPlanYearDetails();
        if(CollectionUtils.isEmpty(planYearDetails)){
            return "数据异常！";
        }

        String currentVersion = exist.getCurrentVersion();
        String nextVersion = (Integer.parseInt(currentVersion)+1)+"";

        PlanYearExample example1 = new PlanYearExample();
        example1.createCriteria().andCurrentVersionEqualTo(nextVersion).andPlanYearEqualTo(planYear.getPlanYear()).andStatusEqualTo(Constants.NORMAL_STATUS);
        int count = planYearMapper.countByExample(example1);
        if(count > 0){
            return "版本v"+nextVersion+"已经存在";
        }
        String existYear = exist.getPlanYear();
        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andPlanYearEqualTo(existYear);
        PlanYear update = new PlanYear();
        update.setLatestVersion("0");
        count = planYearMapper.updateByExampleSelective(update,example);
        if(count < 0){
           return "更新旧版本异常！";
        }

        planYear.setPid(id);
        String newId = CommonUtil.generateRandomNum("planYear-");
        planYear.setId(newId);
        planYear.setCurrentVersion(nextVersion);
        for(PlanYearDetail detail:planYearDetails){
            detail.setPlanYearId(newId);
        }
        count = planYearMapper.insertSelective(planYear);
        if(count < 1){
            throw new Exception("插入年度表异常！");
        }
        String resp = planYearDetailService.addPlanYearDetail(planYearDetails);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updatePlanYear(PlanYear planYear) throws Exception {
        String id = planYear.getId();
        if(StringUtils.isEmpty(id)){
            return "主键为空！";
        }
        PlanYear exist = planYearMapper.selectPlanYearById(id);
        if(null == exist){
            return "未查询到年度计划！";
        }
        String planStatus = exist.getPlanStatus();
        if(!StringUtils.equals(planStatus,"0")&&!StringUtils.equals(planStatus,"5")){
            return "年度计划不在待执行状态，无法编辑";
        }

        List<PlanYearDetail> planYearDetails = planYear.getPlanYearDetails();
        if(CollectionUtils.isEmpty(planYearDetails)){
            return "数据异常！";
        }

        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andIdEqualTo(id);

        int count = planYearMapper.updateByExampleSelective(planYear,example);
        if(count < 1){
            return "更新异常!";
        }
        String resp = planYearDetailService.updatePlanYearDetail(planYearDetails);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public String updateCheckPlanYear(PlanYear planYear) throws Exception {
        if(StringUtils.isEmpty(planYear.getId())){
            return "缺少主键！";
        }

        PlanYear exist = planYearMapper.selectPlanYearById(planYear.getId());
        if(null == exist){
            return "未查询到年度计划！";
        }
        if(!StringUtils.equals(exist.getPlanStatus(),"1")){
            return "年度计划不在待审核状态";
        }
        if(StringUtils.equals(planYear.getPlanStatus(),"2")){
            String year = exist.getPlanYear();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
            String actualYear = simpleDateFormat.format(new Date());
            if(Integer.parseInt(actualYear) < Integer.parseInt(year)){
                planYear.setPlanStatus("3");
            }
        }
        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andIdEqualTo(planYear.getId());
        int count = planYearMapper.updateByExampleSelective(planYear,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deletePlanYearById(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "缺少主键！";
        }
        PlanYear exist = planYearMapper.selectPlanYearById(id);
        if(null == exist){
            return "未查询到年度计划！";
        }
        if(!StringUtils.equals(exist.getPlanStatus(),"0")){
            return "年度计划不在待执行状态，无法删除";
        }
        PlanYear update = new PlanYear();
        update.setStatus(Constants.DEL_STATUS);

        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andIdEqualTo(id);

        int count = planYearMapper.updateByExampleSelective(update,example);
        if(count < 1){
            return "删除数据异常！";
        }
        PlanYear planYear = planYearMapper.selectLatestPlanByYear(exist.getPlanYear());
        if(null != planYear &&StringUtils.isNotEmpty(planYear.getId())){
            PlanYearExample example1 = new PlanYearExample();
            example1.createCriteria().andIdEqualTo(planYear.getId());
            PlanYear update1 = new PlanYear();
            update1.setLatestVersion("1");
            count = planYearMapper.updateByExampleSelective(update1,example1);
            if(count < 1){
                throw new Exception("更新数据异常！");
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public int getCheckPlanYearCount() throws Exception {
        PlanYearExample example = new PlanYearExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPlanStatusEqualTo("1");
        int count = planYearMapper.countByExample(example);
        return count;
    }


    @Scheduled(cron = "0 0 */2 * * ?")
//    @Scheduled(cron = "*/5 * * * * ?")
    public void updateScheduler(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String actualYear = simpleDateFormat.format(new Date());
        PlanYearExample example = new PlanYearExample();
        List<String> statusList = Lists.newArrayList("2","3");
        example.createCriteria().andPlanStatusIn(statusList).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<PlanYear> planYears = planYearMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(planYears)){
            List<PlanYear> updates = Lists.newArrayList();
            for(PlanYear plan:planYears){
                String year = plan.getPlanYear();
                String planStatus = plan.getPlanStatus();
                if(!StringUtils.equals(year,actualYear)&&StringUtils.equals(planStatus,"2")){
                    PlanYear update = new PlanYear();
                    update.setPlanStatus("4");
                    update.setId(plan.getId());
                    updates.add(update);
                }else if(StringUtils.equals(year,actualYear)&&StringUtils.equals(planStatus,"3")){
                    PlanYear update = new PlanYear();
                    update.setPlanStatus("2");
                    update.setId(plan.getId());
                    updates.add(update);
                }
            }
            if(CollectionsUtil.isNotEmpty(updates)){
                planYearMapper.batchUpdatePlanYears(updates);
            }
        }
    }
}
